/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.biz.modular.file.entity.BizFile;
import vip.xiaonuo.biz.modular.file.param.BizFileParam;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.file.entity.BizFileManager;
import vip.xiaonuo.biz.modular.file.mapper.BizFileManagerMapper;
import vip.xiaonuo.biz.modular.file.param.BizFileManagerAddParam;
import vip.xiaonuo.biz.modular.file.param.BizFileManagerEditParam;
import vip.xiaonuo.biz.modular.file.param.BizFileManagerIdParam;
import vip.xiaonuo.biz.modular.fileManager.param.BizFileManagerPageParam;
import vip.xiaonuo.biz.modular.file.service.BizFileManagerService;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.dev.api.DevMessageApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 记录活动文件Service接口实现类
 *
 * @author xsl
 * @date  2024/08/14 16:32
 **/
@Service
public class BizFileManagerServiceImpl extends ServiceImpl<BizFileManagerMapper, BizFileManager> implements BizFileManagerService {


    @Resource
    private DevFileApi devFileApi;

    @Resource
    private DevMessageApi devMessageApi;

    @Resource
    private SysUserApi sysUserApi;

    @Resource
    private BizFileManagerMapper bizFileManagerMapper;

    /**
     * 增加文件上传本地化操作
     * @param fileType
     * @param file
     * @return
     */
    @Override
    public String uploadReturnId(String fileType, MultipartFile file) {
        String fileId = devFileApi.storageFileWithReturnIdLocal(file);
        BizFileManagerAddParam bizFileManagerAddParam = new BizFileManagerAddParam();
        bizFileManagerAddParam.setFileId(fileId);
        bizFileManagerAddParam.setFileStatus(10);
        bizFileManagerAddParam.setFileType(fileType);
        this.add(bizFileManagerAddParam);
        return fileId;
    }

    @Override
    public Page<BizFileManager> page(BizFileManagerPageParam bizFileManagerPageParam) {
        QueryWrapper<BizFileManager> queryWrapper = new QueryWrapper<BizFileManager>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(bizFileManagerPageParam.getSortField(), bizFileManagerPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizFileManagerPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizFileManagerPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizFileManagerPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizFileManager::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFileManagerAddParam bizFileManagerAddParam) {
        BizFileManager bizFileManager = BeanUtil.toBean(bizFileManagerAddParam, BizFileManager.class);
        this.save(bizFileManager);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFileManagerEditParam bizFileManagerEditParam) {
        BizFileManager bizFileManager = this.queryEntity(bizFileManagerEditParam.getId());
        BeanUtil.copyProperties(bizFileManagerEditParam, bizFileManager);
        this.updateById(bizFileManager);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizFileManagerIdParam> bizFileManagerIdParamList) {
        // 执行删除
        List<String> readyDelete = new ArrayList<>();
        for(BizFileManagerIdParam bizFileManagerIdParam : bizFileManagerIdParamList){
            readyDelete.add(bizFileManagerIdParam.getId());
        }
        devFileApi.deleteFile(readyDelete);
        this.removeByIds(CollStreamUtil.toList(bizFileManagerIdParamList, BizFileManagerIdParam::getId));
    }

    @Override
    public BizFileManager detail(BizFileManagerIdParam bizFileManagerIdParam) {
        return this.queryEntity(bizFileManagerIdParam.getId());
    }

    @Override
    public BizFileManager queryEntity(String id) {
        BizFileManager bizFileManager = this.getById(id);
        if(ObjectUtil.isEmpty(bizFileManager)) {
            throw new CommonException("记录活动文件不存在，id值为：{}", id);
        }
        return bizFileManager;
    }



    @Override
    public Page<BizFile> getPageVo(BizFileManagerPageParam bizFileManagerPageParam) {
        Long page = (long) bizFileManagerPageParam.getCurrent();
        Long size = (long) bizFileManagerPageParam.getSize() ;
        Page<BizFile> iPage = new Page<>(page, size);
        if(bizFileManagerPageParam.getSearchKey() == null || bizFileManagerPageParam.getSearchKey().isEmpty() ) return bizFileManagerMapper.getPageVo(iPage);
        else return bizFileManagerMapper.getPageVoByCon(iPage, bizFileManagerPageParam.getSearchKey());
    }

    @Override
    public Page<BizFile> getPageVoPublicity(BizFileManagerPageParam bizFileManagerPageParam) {
        Long page = (long) bizFileManagerPageParam.getCurrent();
        Long size = (long) bizFileManagerPageParam.getCurrent();
        Page<BizFile> iPage = new Page<>(page, size);
        if(bizFileManagerPageParam.getSearchKey() == null || bizFileManagerPageParam.getSearchKey().isEmpty() ) return bizFileManagerMapper.getPageVoPub(iPage);
        else return bizFileManagerMapper.getPageVoPubByCon(iPage, bizFileManagerPageParam.getSearchKey());
    }

    @Override
    public void publicityFile(BizFileParam bizFileParam) {
        String fileMangerId = bizFileParam.getId();
        BizFileManager bizFileManager = this.getById(fileMangerId);
        bizFileManager.setFileStatus(20);
        List<String> receiverIdList = null;
        if(bizFileParam.getNoticeRange().equals("user")) receiverIdList = bizFileParam.getNoticeKeys();
        if(bizFileParam.getNoticeRange().equals("org")) receiverIdList = sysUserApi.getUserIdListByOrgIdList(bizFileParam.getNoticeKeys());
        devMessageApi.sendMessageWithContent(receiverIdList, "BIZ" ,"文件公示","当前文件名为："+bizFileParam.getName()+"正在公示中，请登录“职工之家”网站，点击“文件公示”查阅");
        this.updateById(bizFileManager);
    }

    @Override
    public void resetPub(List<BizFileManagerIdParam> bizFileManagerIdParamList) {
        // 执行删除
        for(BizFileManagerIdParam bizFileManagerIdParam : bizFileManagerIdParamList){
            BizFileManager bizFileManager = this.getById(bizFileManagerIdParam.getId());
            bizFileManager.setFileStatus(10);
            this.updateById(bizFileManager);
        }
    }

    @Override
    public List<String> uploadList(MultipartFile[] files) {
        List<String> fileManagerId = new ArrayList<>();
        for (MultipartFile file : files){
            String fileId = devFileApi.storageFileWithReturnIdLocal(file);
            BizFileManagerAddParam bizFileManagerAddParam = new BizFileManagerAddParam();
            bizFileManagerAddParam.setFileId(fileId);
            bizFileManagerAddParam.setFileStatus(10);
            this.add(bizFileManagerAddParam);
            fileManagerId.add(fileId);
        }
        return fileManagerId;
    }

    @Override
    public List<String> uploadListByTencent(MultipartFile[] files) {
        List<String> fileUrlList = new ArrayList<>();
        for (MultipartFile file : files){
            String fileUrl = devFileApi.storageFileWithReturnUrlTencent(file);
            BizFileManagerAddParam bizFileManagerAddParam = new BizFileManagerAddParam();
            bizFileManagerAddParam.setFileId("腾讯上传");
            bizFileManagerAddParam.setFileStatus(100);
            this.add(bizFileManagerAddParam);
            fileUrlList.add(fileUrl);
        }
        return fileUrlList;
    }

    @Override
    public BizFileManager getByFileId(String fileId) {
        LambdaQueryWrapper<BizFileManager> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizFileManager::getFileId, fileId);
        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    public String getFileUrl(String fileId) {
        JSONObject file = devFileApi.getFileById(fileId);
        Map fileMap = file.toBean(Map.class);
        return (String) fileMap.get("downloadPath");
    }
}
